package app

import (
	"cserver/api/exredis"
	"encoding/json"
	"github.com/go-redis/redis"
	"log"
	"time"
)

var (
	sendID           string
	receiveId        string
	connTime         int64  //时间戳
	rMqRoutingKey    string //接收方的路由key
	sMqRoutingKey    string //发送方的路由key
	rMqExchange      string //接收方的交换机
	sMqExchange      string //发送方的交换机
	rMqQueue         string //接收方消息通道
	sMqQueue         string //发送方消息通道
	consumerName     string //消费者名
	ClientMegsObj    ClientMesg
	ClientStatusByte []byte
	ClientStatusJson string
)

// 客户端消息
type ClientMesg struct {
	SendId    string
	ReceiveId string
}

//存储链接状态
type ClientStatus struct {
	ReceiveId     string //接收方ID
	ConnTime      int64  //时间戳
	RMqRoutingKey string //接收方的路由key
	SMqRoutingKey string //发送方的路由key
	RMqExchange   string //接收方的交换机
	SMqExchange   string //发送方的交换机
	RMqQueue      string //消息通道
	SMqQueue      string //消息通道
	ConsumerName  string //消费者名
}

// 存储客户端信息
func Created(ClientMegs []byte, redisConn *redis.Client) (sendID string, ClientStatusObj ClientStatus, err error) {
	if ClientMegsObj, err = jsonDecode(ClientMegs); err != nil {
		log.Panic(err)
	}
	sendID = ClientMegsObj.SendId
	receiveId = ClientMegsObj.ReceiveId
	rMqRoutingKey = "cserver.receive." + sendID     //接收方的路由key
	sMqRoutingKey = "cserver.send." + receiveId     //发送方的路由key
	rMqExchange = "cserver.exchange." + sendID      //接收方的交换机
	sMqExchange = "cserver.exchange." + receiveId   //发送方的交换机
	rMqQueue = "cserver.queue." + sendID            //接收方消息通道
	sMqQueue = "cserver.queue." + receiveId         //接收方消息通道
	consumerName = "cserver.consumerName." + sendID //消费者名
	connTime = time.Now().Unix()
	ClientStatusObj.ReceiveId = receiveId
	ClientStatusObj.ConnTime = connTime
	ClientStatusObj.RMqRoutingKey = rMqRoutingKey
	ClientStatusObj.SMqRoutingKey = sMqRoutingKey
	ClientStatusObj.RMqExchange = rMqExchange
	ClientStatusObj.SMqExchange = sMqExchange
	ClientStatusObj.RMqQueue = rMqQueue
	ClientStatusObj.SMqQueue = sMqQueue
	ClientStatusObj.ConsumerName = consumerName
	ClientStatusByte, err = jsonEncode(ClientStatusObj)
	ClientStatusJson = string(ClientStatusByte)
	err = exredis.Set(redisConn, sendID, ClientStatusJson)
	return
}

// 解析客户端JSON消息
func jsonDecode(message []byte) (ClientMegsObj ClientMesg, err error) {
	err = json.Unmarshal(message, &ClientMegsObj)
	return
}

func jsonEncode(ClientStatusObj ClientStatus) (ClientStatusByte []byte, err error) {
	ClientStatusByte, err = json.Marshal(ClientStatusObj)
	return
}
